import { ElMessage } from 'element-plus'
import { MsgData } from '@/data/TaskData'
import { close } from '@/api/SSEApi.ts'

let clientId:string = ''
let sseClient:EventSource

export const initSSE = (taskId:string, handle:Function) => {
    if(!window.EventSource){
        ElMessage.error('浏览器不支持SSE')
        return
    }

    if(sseClient && sseClient.readyState == 1){
        return;
    }

    sseClient = new EventSource(import.meta.env.VITE_BASE_SEE + '/sse/conn?taskId=' + taskId + '&id=' + clientId)

    sseClient.onmessage = (e) => {
        clientId = e.lastEventId
        const msgData = JSON.parse(e.data) as MsgData
        handle(msgData)
    }

    sseClient.onerror = () => {
        if(sseClient){
            sseClient.close()
        }
    }
}

export const closeSSE = async (taskId:string) => {
    if(clientId){
        await close(taskId, clientId)
    }

    if(sseClient){
        sseClient.close()
    }
}